
import string
import random
import json
import uuid

from toutiao.cache.redis import redis_client,redis_client1
from flask import Blueprint, request, redirect, session, make_response,g
from werkzeug.security import check_password_hash

user_api = Blueprint('user', __name__, url_prefix='/user')

from toutiao.model.user import User

# from tou
from toutiao.jwt_yz import create_token


@user_api.route('/get_code', methods=['get'])
def get_code():
    code= "".join(random.choices(string.ascii_letters + string.digits, k=4))
    print(code)
    redis_client1.set('code',code,ex=1800)
    return code

import base64

@user_api.route('/login', methods=['post'])
def login():
    print(request.data)

    username = request.form.get('username', "")
    password = request.form.get('password', "")
    phone = request.form.get("phone", "")
    print(phone)
    code = request.form.get("code", "")
    print(User.query.all())
    user = User.query.filter(User.phone == phone).first()
    if not user:
        return {"code": "20000", "message": "用户不存在"}
    else:
        sd=redis_client1.get("code")

        print(sd.decode())
        if code==sd.decode():
            # todo: 校验验证码，成功或失败
            # todo: 失败
            # 假如成功
            #session['uid'] = user.id
            # 1、将user信息（脱敏）保存到redis中，设置有效时间为30min
            # User(avatar=username,password=password,phone=phone)
            user_info = {
                "id": user.id,
                "username": user.avatar,
                "sex": user.sex
            }


            # 返回一串cookie，同时按照规范返回
            cookie = create_token(username, password)
            print(cookie)
            resp = make_response({"code": 200, "message": "登录成功",'token':cookie})
            resp.set_cookie("token", cookie)
            redis_client.set(cookie, json.dumps(user_info), ex=3600)
            return resp

from functools import wraps
def login_Re(func):
    @wraps(func)
    def h(*args, **kwargs):

        token = request.cookies.get('token')
        if not token:
            return {'code': 500, "msg": '没有找到cookie'}
        sd = redis_client.get(token)
        if sd:
            sd1 = json.loads(sd)
            user_id = sd1['id']
            session['user_id']=user_id
            redis_client.set(token, sd, ex=3600)
        else:
            return {'code': 500, "msg": f'麻烦请先登录'}




        return func(*args, **kwargs)
    return h

from toutiao.model.j import db
@user_api.route('/ed',methods=['post'])
@login_Re
def editor_user():
    user_id = session.get('user_id')  # 发起方
    sex1=request.form.get('sex')
    phone1=request.form.get('phone')
    avatar1=request.form.get('avatar')
    u=User.query.filter_by(id=user_id).first()
    print(u.sex)
    u.sex=sex1
    u.phone=phone1
    u.avatar=avatar1
    db.session.commit()
    return {'code': 200, "msg": '修改成功'}


@user_api.route('/ck',methods=['get'])
@login_Re
def find_user():
    user_id = session.get('user_id')
    u=User.query.filter_by(id=user_id).first()
    cot={
        'avatar':u.avatar,
        'sex':u.sex,
        'phone':u.phone,
        'fans_count':u.fans_count,
        'following_count': u.following_count
    }
    return {'code': 200, "msg": cot}

